package com.changgou.item.controller;

import com.changgou.entity.Page;
import com.changgou.search.feign.SearchFeign;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Set;

/**
 * 老大哥在看着你
 *
 * @author ANG.YU
 * @date 2019-10-11 15:50
 */
@Controller
@RequestMapping("/wsearch")
public class WebSearchController {
    @Autowired
    private SearchFeign searchFeign;

    @GetMapping("/list")
    public String wSearch(@RequestParam Map<String,String> searchMap, Model model) {
        searchMap = replaceSpec(searchMap);

        Map<String, Object> mapResult = searchFeign.search(searchMap);

        model.addAttribute("result", mapResult);
        model.addAttribute("searchMap", searchMap);
        model.addAttribute("page",new Page(
                (Integer)mapResult.get("total"),
                Integer.parseInt(String.valueOf(mapResult.get("pageNum"))),
                Page.pageSize
        ));

        StringBuilder url = new StringBuilder();

        url.append("/wsearch/list");

        if (!StringUtils.isEmpty(searchMap.get("keywords"))) {
            url.append("?").append("keywords=").append(searchMap.get("keywords"));
        }
        if (!StringUtils.isEmpty(searchMap.get("brand"))) {
            url.append("&").append("brand=").append(searchMap.get("brand"));
        }

        if (!StringUtils.isEmpty(searchMap.get("price"))) {
            url.append("&").append("price=").append(searchMap.get("price"));
        }
        if (!StringUtils.isEmpty(searchMap.get("sortRule"))) {
            url.append("&").append("sortRule=").append(searchMap.get("sortRule"));
        }
        if (!StringUtils.isEmpty(searchMap.get("sortField"))) {
            url.append("&").append("sortField=").append(searchMap.get("sortField"));
        }


        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().contains("spec_")) {
                url.append("&").append(entry.getKey()).append("=").append(entry.getValue());
            }
        }

        model.addAttribute("url", url);
        return "search";
    }
    //搜索页面之过滤条件规格特殊符号处理
    private Map<String, String> replaceSpec(Map<String, String> searchMap) {
        Set<Map.Entry<String, String>> entries = searchMap.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            if (entry.getKey().contains("spec_")) {
                searchMap.put(entry.getKey(), entry.getValue().replace("+", "%2B"));
            }
        }
        return searchMap;
    }

}
